{
 "cells": [
  {
   "metadata": {},
   "cell_type": "raw",
   "source": "# 5.输出解析器（Output Parser）负责获取 LLM 的输出并将其转换为更合适的格式",
   "id": "ceaea883034646c3"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:23:25.134337Z",
     "start_time": "2025-10-25T06:23:24.375404Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#5.2 具体解析器的使用\n",
    "# 举例1：将一个对话模型的输出结果，解析为字符串输出\n",
    "from langchain_core.messages import HumanMessage, SystemMessage\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"DASHSCOPE_API_KEY\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"DASHSCOPE_BASE_URL\")\n",
    "chat_model = ChatOpenAI(model=\"qwen-max\")\n",
    "messages = [\n",
    "    SystemMessage(content=\"将以下内容从英语翻译成中文\"),\n",
    "    HumanMessage(content=\"It's a nice day today\"),\n",
    "]\n",
    "result = chat_model.invoke(messages)\n",
    "print(type(result)) #AIMessage\n",
    "print(result)\n",
    "parser = StrOutputParser()\n",
    "#使用parser处理model返回的结果\n",
    "response = parser.invoke(result)\n",
    "print(type(response)) #str\n",
    "print(response) #今天天气不错"
   ],
   "id": "d6a8e38ca3973577",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'langchain_core.messages.ai.AIMessage'>\n",
      "content='今天天气不错。' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 4, 'prompt_tokens': 27, 'total_tokens': 31, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_name': 'qwen-max', 'system_fingerprint': None, 'id': 'chatcmpl-f9eb6747-3c61-4f30-bdfe-9baae721659e', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--a4df7727-e11c-4dbf-933a-6b9b3521cad0-0' usage_metadata={'input_tokens': 27, 'output_tokens': 4, 'total_tokens': 31, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}\n",
      "<class 'str'>\n",
      "今天天气不错。\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:26:32.377248Z",
     "start_time": "2025-10-25T06:26:28.692619Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#举例2：JsonOutputParser，即JSON输出解析器，是一种用于将大模型的 自由文本输出 转换为 结构化JSON数据的工具。\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"qwen-max\")\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个靠谱的{role}\"),\n",
    "    (\"human\", \"{question}\")\n",
    "])\n",
    "parser = JsonOutputParser()\n",
    "# 方式1：\n",
    "result = chat_model.invoke(chat_prompt_template.format_messages(\n",
    "    role=\"人工智能专家\",\n",
    "    question=\"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式\"))\n",
    "print(result)\n",
    "print(type(result))\n",
    "parser.invoke(result)\n",
    "# 方式2：\n",
    "chain = chat_prompt_template | chat_model | parser\n",
    "chain.invoke({\"role\":\"人工智能专家\",\n",
    "\"question\" : \"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式\"})"
   ],
   "id": "84e112c572796ba2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='{\\n  \"q\": \"人工智能用英文怎么说？\",\\n  \"a\": \"人工智能用英文说是 Artificial Intelligence，通常缩写为 AI。\"\\n}' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 32, 'prompt_tokens': 39, 'total_tokens': 71, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_name': 'qwen-max', 'system_fingerprint': None, 'id': 'chatcmpl-26e44254-8213-4b3e-b189-acd686fc7a51', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--7ac4e88a-d7cb-478b-a3c6-617587f7e567-0' usage_metadata={'input_tokens': 39, 'output_tokens': 32, 'total_tokens': 71, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}\n",
      "<class 'langchain_core.messages.ai.AIMessage'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'q': '人工智能用英文怎么说？', 'a': '人工智能用英文说是 Artificial Intelligence，通常缩写为 AI。'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:40:12.314834Z",
     "start_time": "2025-10-25T06:40:11.352070Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 举例2：使用指定的JSON格式\n",
    "# 引入依赖包\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "# 初始化语言模型\n",
    "# chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "# joke_query = \"告诉我一个笑话。\"\n",
    "\n",
    "# 定义Json解析器\n",
    "parser = JsonOutputParser()\n",
    "# 定义提示词模版\n",
    "# 注意，提示词模板中需要部分格式化解析器的格式要求format_instructions\n",
    "prompt = PromptTemplate(\n",
    "    template=\"回答用户的查询.\\n{format_instructions}\\n{query}\\n\",\n",
    "    input_variables=[\"query\"],\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "# 5.使用LCEL语法组合一个简单的链\n",
    "chain = prompt | chat_model | parser\n",
    "# 6.执行链\n",
    "output = chain.invoke({\"query\": \"给我讲一个笑话\"})\n",
    "print(output)"
   ],
   "id": "58d23cd163705b73",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'joke': '为什么电脑经常生病？因为它的窗户（Windows）总是开着！'}\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:44:09.855471Z",
     "start_time": "2025-10-25T06:43:51.976023Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 5.3 XML解析器 XMLOutputParser\n",
    "# 举例1：不使用XMLOutputParser，通过大模型的能力，返回xml格式数据\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"qwen-max\")\n",
    "# 测试模型的xml解析效果\n",
    "actor_query = \"生成汤姆·汉克斯的简短电影记录\"\n",
    "output = chat_model.invoke(f\"\"\"{actor_query}请将影片附在<movie></movie>标签中\"\"\"\n",
    ")\n",
    "print(type(output)) # <class 'langchain_core.messages.ai.AIMessage'>\n",
    "print(output.content)"
   ],
   "id": "dc2429080288198e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'langchain_core.messages.ai.AIMessage'>\n",
      "汤姆·汉克斯是一位美国著名演员、导演和制片人，以其多样化的角色而闻名。下面是一些他参与过的著名电影作品列表：\n",
      "\n",
      "- <movie>《阿甘正传》(Forrest Gump, 1994)</movie> - 在这部电影中，汤姆·汉克斯饰演了主角福雷斯特·冈普，这是一部讲述了一个智商只有75的好心人如何影响了美国几十年历史的故事。\n",
      "- <movie>《拯救大兵瑞恩》(Saving Private Ryan, 1998)</movie> - 汤姆在这部由史蒂文·斯皮尔伯格执导的战争片里扮演了一名美军上尉，该片以诺曼底登陆为背景，讲述了寻找并安全带回一名士兵的故事。\n",
      "- <movie>《荒岛余生》(Cast Away, 2000)</movie> - 这部影片讲述了汤姆·汉克斯饰演的角色查克·诺兰德在一次飞机失事后被困在一个无人岛上四年多的经历。\n",
      "- <movie>《达芬奇密码》(The Da Vinci Code, 2006)</movie> - 基于丹·布朗同名小说改编，汤姆·汉克斯在其中扮演符号学家罗伯特·兰登博士，解开一系列神秘谜题。\n",
      "- <movie>《萨利机长》(Sully, 2016)</movie> - 讲述了切斯利·萨伦伯格（汤姆·汉克斯饰）作为飞行员，在遇到鸟击后成功迫降哈德逊河上的真实故事。\n",
      "\n",
      "这些只是汤姆·汉克斯辉煌职业生涯中的几部代表作。他的表演深受观众喜爱，并且多次获得奥斯卡金像奖的认可。\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:45:49.697094Z",
     "start_time": "2025-10-25T06:45:49.672996Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 举例2：体会XMLOutputParser的格式\n",
    "from langchain_core.output_parsers import XMLOutputParser\n",
    "output_parser = XMLOutputParser()\n",
    "# 返回一些指令或模板，这些指令告诉系统如何解析或格式化输出数据\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)"
   ],
   "id": "5e4521a87a0494ec",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The output should be formatted as a XML file.\n",
      "1. Output should conform to the tags below.\n",
      "2. If tags are not given, make them on your own.\n",
      "3. Remember to always open and close all the tags.\n",
      "\n",
      "As an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n",
      "1. String \"<foo>\n",
      "   <bar>\n",
      "      <baz></baz>\n",
      "   </bar>\n",
      "</foo>\" is a well-formatted instance of the schema.\n",
      "2. String \"<foo>\n",
      "   <bar>\n",
      "   </foo>\" is a badly-formatted instance.\n",
      "3. String \"<foo>\n",
      "   <tag>\n",
      "   </tag>\n",
      "</foo>\" is a badly-formatted instance.\n",
      "\n",
      "Here are the output tags:\n",
      "```\n",
      "None\n",
      "```\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:48:34.366863Z",
     "start_time": "2025-10-25T06:48:19.824630Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 举例3：XMLOutputParser 的使用\n",
    "# 1.导入相关包\n",
    "from langchain_core.output_parsers import XMLOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 2. 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"qwen-max\")\n",
    "# 3.测试模型的xml解析效果\n",
    "actor_query = \"生成汤姆·汉克斯的简短电影记录,使用中文回复\"\n",
    "# 4.定义XMLOutputParser对象\n",
    "parser = XMLOutputParser()\n",
    "# 5.定义提示词模版对象\n",
    "# prompt = PromptTemplate(\n",
    "# template=\"{query}\\n{format_instructions}\",\n",
    "# input_variables=[\"query\",\"format_instructions\"],\n",
    "# partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    "#)\n",
    "prompt_template = PromptTemplate.from_template(\"{query}\\n{format_instructions}\")\n",
    "prompt_template1 =prompt_template.partial(format_instructions=parser.get_format_instructions())\n",
    "response = chat_model.invoke(prompt_template1.format(query=actor_query))\n",
    "print(response.content)"
   ],
   "id": "a9276a4fe7e3b77e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "由于没有提供具体的标签要求，我将根据常见的XML结构自定义一些标签来展示汤姆·汉克斯的简短电影记录。这包括了演员的基本信息和他的部分著名作品列表。\n",
      "\n",
      "```xml\n",
      "<Actor>\n",
      "    <Name>汤姆·汉克斯</Name>\n",
      "    <BirthDate>1956-07-09</BirthDate>\n",
      "    <Nationality>美国</Nationality>\n",
      "    <Movies>\n",
      "        <Movie>\n",
      "            <Title>阿甘正传</Title>\n",
      "            <Year>1994</Year>\n",
      "            <Role>福雷斯特·冈普</Role>\n",
      "        </Movie>\n",
      "        <Movie>\n",
      "            <Title>拯救大兵瑞恩</Title>\n",
      "            <Year>1998</Year>\n",
      "            <Role>约翰·米勒上尉</Role>\n",
      "        </Movie>\n",
      "        <Movie>\n",
      "            <Title>荒岛余生</Title>\n",
      "            <Year>2000</Year>\n",
      "            <Role>查克·诺兰德</Role>\n",
      "        </Movie>\n",
      "        <Movie>\n",
      "            <Title>达芬奇密码</Title>\n",
      "            <Year>2006</Year>\n",
      "            <Role>罗伯特·兰登教授</Role>\n",
      "        </Movie>\n",
      "    </Movies>\n",
      "</Actor>\n",
      "```\n",
      "\n",
      "这段XML代码定义了一个`<Actor>`元素，其中包含了关于汤姆·汉克斯的一些基本信息（如名字、出生日期和国籍），以及他参与过的几部知名电影的信息。每部电影都通过`<Movie>`标签来表示，并且每个`<Movie>`标签内又包含了电影的名字、上映年份以及他在该电影中扮演的角色名称。\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:51:42.134634Z",
     "start_time": "2025-10-25T06:51:26.800595Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 方式1\n",
    "response = chat_model.invoke(prompt_template1.format(query=actor_query))\n",
    "result = parser.invoke(response)\n",
    "print(result)\n",
    "print(type(result))\n",
    "# 方式2\n",
    "# chain = prompt_template1 | chat_model | parser\n",
    "# result = chain.invoke({\"query\":actor_query})\n",
    "# print(result)\n",
    "# print(type(result))"
   ],
   "id": "f896f4c9f434c09",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'actor': [{'name': '汤姆·汉克斯'}, {'birth': '1956年7月9日'}, {'birthplace': '美国加利福尼亚州康科德'}, {'careerHighlights': [{'highlight': '两度获得奥斯卡最佳男主角奖（《费城故事》(1993)与《阿甘正传》(1994)）。'}, {'highlight': '因在多部影片中的出色表现而广受赞誉，被认为是当代最伟大的演员之一。'}]}, {'notableWorks': [{'movie': [{'title': '拯救大兵瑞恩'}, {'year': '1998'}, {'role': '约翰·米勒上尉'}]}, {'movie': [{'title': '阿甘正传'}, {'year': '1994'}, {'role': '福雷斯特·冈普'}]}, {'movie': [{'title': '荒岛余生'}, {'year': '2000'}, {'role': '查克·诺兰'}]}, {'movie': [{'title': '达芬奇密码'}, {'year': '2006'}, {'role': '罗伯特·兰登教授'}]}]}]}\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:56:26.919880Z",
     "start_time": "2025-10-25T06:56:13.351034Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 举例4：与前例类似\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_core.output_parsers import XMLOutputParser\n",
    "model = ChatOpenAI(model=\"qwen-max\")\n",
    "actor_query = \"生成周星驰的简化电影作品列表，按照最新的时间降序，必要时使用中文\"\n",
    "# 设置解析器 + 将指令注入提示模板。\n",
    "parser = XMLOutputParser()\n",
    "prompt = PromptTemplate(\n",
    "template=\"回答用户的查询。\\n{format_instructions}\\n{query}\\n\",\n",
    "input_variables=[\"query\"],\n",
    "partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "chain = prompt | model | parser\n",
    "output = chain.invoke({\"query\": actor_query})\n",
    "print(output)"
   ],
   "id": "9a49bb73e4ffedc2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'电影作品列表': [{'电影': [{'名称': '新喜剧之王'}, {'年份': '2019'}]}, {'电影': [{'名称': '美人鱼'}, {'年份': '2016'}]}, {'电影': [{'名称': '西游降魔篇'}, {'年份': '2013'}]}, {'电影': [{'名称': '长江七号'}, {'年份': '2008'}]}, {'电影': [{'名称': '功夫'}, {'年份': '2004'}]}, {'电影': [{'名称': '少林足球'}, {'年份': '2001'}]}, {'电影': [{'名称': '喜剧之王'}, {'年份': '1999'}]}, {'电影': [{'名称': '食神'}, {'年份': '1996'}]}, {'电影': [{'名称': '大话西游之大圣娶亲'}, {'年份': '1995'}]}, {'电影': [{'名称': '国产凌凌漆'}, {'年份': '1994'}]}]}\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T06:58:58.588244Z",
     "start_time": "2025-10-25T06:58:58.524073Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 列表解析器 CommaSeparatedListOutputParser\n",
    "from langchain_core.output_parsers import CommaSeparatedListOutputParser\n",
    "output_parser = CommaSeparatedListOutputParser()\n",
    "# 返回一些指令或模板，这些指令告诉系统如何解析或格式化输出数据\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)\n",
    "messages = \"大象,猩猩,狮子\"\n",
    "result = output_parser.parse(messages)\n",
    "print(result)\n",
    "print(type(result))"
   ],
   "id": "9ba8947451b3b079",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`\n",
      "['大象', '猩猩', '狮子']\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T07:00:43.319018Z",
     "start_time": "2025-10-25T07:00:40.742798Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 举例2：\n",
    "# 创建LangChain提示模板\n",
    "chat_prompt = PromptTemplate.from_template(\n",
    "    \"生成5个关于{text}的列表.\\n\\n{format_instructions}\",\n",
    "    partial_variables={\n",
    "        \"format_instructions\": output_parser.get_format_instructions()\n",
    "    })\n",
    "# 提示模板与输出解析器传递输出\n",
    "# chat_prompt =\n",
    "chat_prompt.partial(format_instructions=output_parser.get_format_instructions())\n",
    "# 将提示和模型合并以进行调用\n",
    "chain = chat_prompt | chat_model | output_parser\n",
    "res = chain.invoke({\"text\": \"电影\"})\n",
    "print(res)\n",
    "print(type(res))"
   ],
   "id": "6d75876e9c3f9406",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['最佳科幻电影', '经典爱情故事', '顶级动画长片', '著名导演作品', '高评分纪录片']\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T07:03:08.911779Z",
     "start_time": "2025-10-25T07:03:07.823718Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 举例3：\n",
    "# 创建LangChain提示模板\n",
    "chat_prompt = ChatPromptTemplate.from_messages([\n",
    "(\"human\", \"{request}\\n{format_instructions}\")\n",
    "# HumanMessagePromptTemplate.from_template(\"{request}\\n{format_instructions}\"),\n",
    "])\n",
    "# 提示模板与输出解析器传递输出\n",
    "# chat_prompt =\n",
    "chat_prompt.partial(format_instructions=output_parser.get_format_instructions())\n",
    "# 将提示和模型合并以进行调用\n",
    "chain = chat_prompt | chat_model | output_parser\n",
    "resp = chain.invoke({\"request\": \"给我5个心情\", \"format_instructions\":\n",
    "output_parser.get_format_instructions()})\n",
    "print(resp)\n",
    "print(type(resp))"
   ],
   "id": "3955d25a428ce1ab",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['开心', '平静', '忧郁', '兴奋', '烦躁']\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T07:39:49.569226Z",
     "start_time": "2025-10-25T07:39:49.302464Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 5 日期解析器 DatetimeOutputParser\n",
    "# 举例1\n",
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "output_parser = DatetimeOutputParser()\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)"
   ],
   "id": "ea350181e850e8ab",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Write a datetime string that matches the following pattern: '%Y-%m-%dT%H:%M:%S.%fZ'.\n",
      "\n",
      "Examples: 0078-02-15T05:52:00.684194Z, 0888-12-10T20:59:34.760006Z, 1309-04-19T09:29:17.813789Z\n",
      "\n",
      "Return ONLY this string, no other words!\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-25T07:42:32.951209Z",
     "start_time": "2025-10-25T07:42:31.173747Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 举例2\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.prompts.chat import HumanMessagePromptTemplate\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "\n",
    "# chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "chat_prompt = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"{format_instructions}\"),\n",
    "    (\"human\", \"{request}\")\n",
    "])\n",
    "output_parser = DatetimeOutputParser()\n",
    "# 方式2：\n",
    "chain = chat_prompt | chat_model | output_parser\n",
    "resp = chain.invoke({\"request\": \"中华人民共和国是什么时候成立的？\",\n",
    "                     \"format_instructions\": output_parser.get_format_instructions()})\n",
    "print(resp) #1949-10-01 00:00:00\n",
    "print(type(resp)) #datetime"
   ],
   "id": "c022b3bc1862ba35",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1949-10-01 00:00:00\n",
      "<class 'datetime.datetime'>\n"
     ]
    }
   ],
   "execution_count": 26
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
